/*
 *  Copyright 2010 Wesley Gooch, Ryan Nix, Cody Wenzel.
 *  Montana State University - Spring Semester 2010
 *  Computer Science 450 - Compilers
 *  Project: Micro-Pascal Compiler
 */
package msu.compiler.semantics;

import msu.compiler.codegenerators.LabelGen;
import java.util.HashMap;
import msu.compiler.errorhandling.CompileException;

/**
 *
 * @author wenzel
 */
public class SymbolTable {

    protected String name;
    protected SymbolTable parent;
    protected byte scopeDepth;
    protected HashMap<String, Symbol> symbols;
    protected byte size;

    public int getNestLevel() {
        return nestLevel;
    }
    protected int nestLevel;
    protected String label;

    public SymbolTable(String name) {
        this.name = name;
        symbols = new HashMap<String, Symbol>();
        this.label = LabelGen.getLabelGen().getLabel();
    }

    public SymbolTable(String name, String label) {
        this.name = name;
        symbols = new HashMap<String, Symbol>();
        this.label = label;
    }

    public void insertSymbol(Symbol symbol) throws CompileException {
        symbol.setOffset(size);
        size = (byte) (size + 1);
        if (!symbols.containsKey(symbol.getLexeme())) {
            symbols.put(symbol.getLexeme(), symbol);
        } else {
            throw new CompileException("Identifier " + symbol.getLexeme() + " has already been declared.", symbol.getToken());
        }
    }

    public void incrementSize() {
        size++;
    }

    public Symbol lookupSymbol(String lexeme) {
        if (symbols.containsKey(lexeme)) {
            return symbols.get(lexeme);
        } else {
            return null;
        }
    }

    public SymbolTable getParent() {
        return parent;
    }

    public void setParent(SymbolTable parent) {
        this.parent = parent;
    }

    @Override
    public String toString() {
        return "Table Name:" + name + " " + "Nest:" + nestLevel + " " + "Size:" + size + " Label:" + label;
    }

    public int getSize(){
        return symbols.size();
    }

    public String getName(){
        return name;
    }

    public String getLabel(){
        return label;
    }
}
